const path = require('path')
const { app, session, BrowserWindow, globalShortcut, screen, dialog  } = require('electron')
const { saveConsoleLog, saveAPPLog, saveErrorLog } = require('./log');

const windows = {};

function setWinSizePosition(win, config){
    const { width, height } = screen.getPrimaryDisplay().workAreaSize;
    win.setSize(
        config?.width ?? Math.ceil(width*0.75), 
        config?.height ?? Math.ceil(height*0.75)
    )
    win.setMinimumSize(
        config?.minWidth ?? Math.ceil(width*0.75), 
        config?.minHeight ?? Math.ceil(height*0.75)
    )
    win.setPosition(
        config?.x ?? Math.ceil(width*0.125) + Object.keys(windows).length * 40, 
        config?.y ?? Math.ceil(height*0.125) + Object.keys(windows).length * 40
    )
}

function getIconPath(){
    const iconPath = path.join(__dirname, 
        process.platform === 'win32' ? 'icon/icon.ico' :  // Windows 用 ICO
        process.platform === 'darwin' ? 'icon/icon.icns' : // macOS 用 ICNS
        'icon/icon.png' // Linux 用 PNG
    );

    return iconPath
}

const createWindow = (url = 'http://localhost:18887', config = {}) => {
    
    const winKey = decodeURIComponent(url || 'default')

    if (windows[winKey] && !windows[winKey].isDestroyed()) {
        windows[winKey].show()
        return windows[winKey];
    }

    const { width, height } = screen.getPrimaryDisplay().workAreaSize
    const win = new BrowserWindow({
        width: Math.ceil(width*0.75),
        height: Math.ceil(height*0.75),
        //设置为 false 时可以创建一个无边框窗口 默认值为 true。
        frame: false,
        //窗口是否在创建时显示。 默认值为 true。
        show: true,
        icon: getIconPath(),
        ...config,
        webPreferences: {
            charset: 'utf-8',
            nodeIntegration: true,	//启用nodejs
			enableRemoteModule: true,	//在electron 10以后的版本，默认是关闭的
			contextIsolation: false,//Electron 12版本之后将默认启用它，使用require()时要关闭contextIsolation
            // CSP: "default-src 'self' 'unsafe-eval' http: https:", // 允许加载 http 和 https 的资源
            ...(config.webPreferences ?? {})
        }
    })

    // setWinSizePosition(win)

    // 设置菜单
    win.setMenu(null)

    win.loadURL(url)
    win.webContents.reloadIgnoringCache()
    
    win.on('focus', () => {
        globalShortcut.register('F5', () => {
            win.webContents.reload();
        });
        globalShortcut.register('Ctrl+F5', () => {
            win.webContents.reloadIgnoringCache();
        });
        globalShortcut.register('F2', () => {
            !win.webContents.isDevToolsOpened() ? win.webContents.openDevTools() : win.webContents.closeDevTools();
        });
        
    });

    // 控制台日志
    win.webContents.on('console-message', (event, level, message) => {
        const levelMap = ['log', 'warning', 'error', 'info'];
        saveConsoleLog(levelMap[level], message);
    });

    // 捕获加载错误
    win.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
        saveErrorLog('页面加载失败：', errorCode, errorDescription, event);
    });
    // 进程崩溃（替代下方旧版 crashed 事件）
    win.webContents.on('render-process-gone', (event, details) => {
        saveErrorLog('渲染进程崩溃:', details, event);
    });

    // 渲染进程 “崩溃”
    win.webContents.on('crashed', (e, reason, exitCode) => {
        const reasons = {
            oom: '内存溢出导致崩溃',
            killed: '进程被系统终止，请检查是否有安全软件拦截',
            normal: '页面意外崩溃'
        }
		saveErrorLog('渲染进程 “崩溃”:', { 
            reason: reasons[reason] || reasons.normal, 
            exitCode,
            platform: process.platform,
        }, e);
	});

    // 渲染进程 “卡死”
    win.on('unresponsive', (event) => {
        saveErrorLog('渲染进程 “卡死”:', event);
    })

    windows[winKey] = win

    return win
}

module.exports = {
    createWindow
};